/**
 * 模拟服务工具
 * 当后端API不可用或尚未完成时，提供模拟数据响应
 */

import { LoginRequest, LoginResponse } from '../api/auth';

// 模拟验证码图片URL (使用在线服务生成的图片)
const MOCK_CAPTCHA_URLS = [
  'https://dummyimage.com/120x40/4a90e2/fff&text=1234',
  'https://dummyimage.com/120x40/4a90e2/fff&text=5678',
  'https://dummyimage.com/120x40/4a90e2/fff&text=ABCD',
  'https://dummyimage.com/120x40/4a90e2/fff&text=EFGH'
];

// 模拟用户数据
const MOCK_USERS = [
  {
    id: '1',
    username: 'admin',
    password: 'admin123',
    name: '管理员',
    email: 'admin@example.com',
    role: 'admin',
    avatar: 'https://randomuser.me/api/portraits/men/1.jpg'
  },
  {
    id: '2',
    username: 'user',
    password: 'user123',
    name: '普通用户',
    email: 'user@example.com',
    role: 'user',
    avatar: 'https://randomuser.me/api/portraits/women/2.jpg'
  }
];

// 检查是否启用了模拟服务
const isMockEnabled = () => {
  return import.meta.env.VITE_ENABLE_MOCK === 'true';
};

// 模拟延迟
const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));

// 模拟服务
const mockService = {
  // 判断是否使用模拟数据
  shouldUseMock: (endpoint: string): boolean => {
    if (!isMockEnabled()) return false;
    
    // 可以根据具体的endpoint决定是否使用模拟数据   const mockEndpoints = ['/auth/register'];
    const mockEndpoints = [];
    return mockEndpoints.some(mockEndpoint => endpoint.includes(mockEndpoint));
  },
  
  // 模拟登录
  mockLogin: async (data: LoginRequest): Promise<LoginResponse> => {
    await delay(800); // 模拟网络延迟
    
    const user = MOCK_USERS.find(u => u.username === data.username);
    
    if (!user) {
      return {
        success: false,
        message: '用户不存在'
      };
    }
    
    if (user.password !== data.password) {
      return {
        success: false,
        message: '密码错误'
      };
    }
    
    // 如果需要验证码验证
    if (data.captcha) {
      // 这里简化处理，实际应该与服务器存储的验证码比对
      if (!['1234', '5678', 'ABCD', 'EFGH'].includes(data.captcha)) {
        return {
          success: false,
          message: '验证码错误'
        };
      }
    }
    
    // 登录成功
    return {
      success: true,
      message: '登录成功',
      data: {
        token: `mock-token-${user.id}-${Date.now()}`,
        user: {
          id: user.id,
          username: user.username,
          name: user.name,
          email: user.email,
          role: user.role,
          avatar: user.avatar
        }
      }
    };
  },
  
  // 模拟获取验证码
  mockCaptcha: async (): Promise<Blob> => {
    await delay(500); // 模拟网络延迟
    
    // 随机选择一个模拟验证码图片
    const randomUrl = MOCK_CAPTCHA_URLS[Math.floor(Math.random() * MOCK_CAPTCHA_URLS.length)];
    
    // 从URL获取图片数据并转换为Blob
    const response = await fetch(randomUrl);
    return await response.blob();
  }
};

export default mockService; 